package com.sjq.demo.service.impl;

import com.baomidou.shaun.core.mgt.SecurityManager;
import com.baomidou.shaun.core.profile.TokenProfile;
import com.sjq.demo.entity.RbacPermission;
import com.sjq.demo.entity.RbacRole;
import com.sjq.demo.entity.RbacUser;
import com.sjq.demo.service.LoginService;
import com.sjq.demo.service.RbacPermissionService;
import com.sjq.demo.service.RbacRoleService;
import com.sjq.demo.service.RbacUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@AllArgsConstructor
public class LoginServiceImpl implements LoginService {


    private final SecurityManager securityManager;

    private RbacUserService rbacUserService;

    private RbacRoleService rbacRoleService;

    private RbacPermissionService rbacPermissionService;

    @Transactional
    @Override
    public String login(String username,String password) {
        Set<String> roleSet = new HashSet<>();
        Set<String> permissionSet = new HashSet<>();
        //通过用户名和密码获取用户信息表
        RbacUser rbacUser = rbacUserService.getRbacUser(username,password);
        //通过rbacUser表id查询角色信息
        List<RbacRole> roles = rbacRoleService.getRolesByUserId(rbacUser.getId().toString());
        for(RbacRole role : roles){
            roleSet.add(role.getRolename());
            //通过角色id获取权限
            List<RbacPermission> permissions = rbacPermissionService.getPermissions(role.getId().toString());
            for(RbacPermission permission : permissions){
                permissionSet.add(permission.getName());
            }
        }
        final TokenProfile profile = new TokenProfile();
        profile.setId(rbacUser.getId().toString());
        profile.setRoles(roleSet);
        profile.setPermissions(permissionSet);
        final String token = securityManager.login(profile);
        return token;
    }
}
